/**
 * 测试用例生成接口测试用例
 *
 * Created by snowingsea on 2020/03/13.
 */
const chai = require('chai');
const should = chai.should(); // eslint-disable-line no-unused-vars
chai.use(require('chai-http'));

const common = require('./../../common');
const Administrator = require('./../../../models/administrator');
const uri = require('./../uri');
const benchmarks = [require('./../../../benchmark/generate-tests/self_designed')];

const tasks = require('./../../../../phoenix/models/tasks');

module.exports = describe('/POST project-versions/:id/tests.json', function () {
  const administrator = new Administrator();
  let project = {};
  const newUserIds = [];
  function url(versionId) {
    return `/project-versions/${versionId}/tests.json`;
  }

  before(function (done) {
    administrator.login()
      .then(() => administrator.createRandomTester())
      .then((tester) => {
        newUserIds.push(tester.userId);
        return tester.createRandomProject();
      })
      .then((res) => {
        project = res;
        done();
      })
      .catch(done);
  });
  after(function (done) {
    administrator.removeUsers(newUserIds)
      .then(() => {
        done();
      })
      .catch(done);
  });

  common.should.be.user(uri, url, 'post');
  common.should.be.tester(uri, url, 'post');

  // 正常发起请求
  benchmarks.forEach((benchmark) => {
    it(`it should generate all tests of ${benchmark.name}`, function (done) {
      let projectVersion;
      let allFunctions;
      project.createRandomVersion()
        .then((res) => {
          projectVersion = res;
          return projectVersion.getAllFunctions(benchmark);
        })
        .then((res) => {
          allFunctions = res;
          return project.creator.login();
        })
        .then(() => {
          chai.request(uri)
            .post(url(projectVersion.versionId))
            .set('Authorization', `Bearer ${project.creator.token.accessToken}`)
            .end((err, res) => {
              res.should.have.status(202);
              common.should.be.taskMessage(res.body);
              res.body.type.should.be.eql(tasks.type.testCaseGenerate);
              res.body.status.should.be.eql(tasks.statusKind.waiting);
              res.body.progress.should.be.eql(0);

              project.creator.waiting4TasksOfVersionFinished(projectVersion.versionId)
                .then(() => {
                  // 查询测试用例
                  const promises = allFunctions.map((func) => {
                    const { functionId } = func;
                    return new Promise((resolve, reject) => {
                      chai.request(uri)
                        .get(`/functions/${functionId}/tests.json`)
                        .set('Authorization', `Bearer ${project.creator.token.accessToken}`)
                        .end((err, res) => {
                          err ? reject(err) : resolve(res.body.tests);
                        });
                    });
                  });
                  return Promise.all(promises);
                })
                .then((allTests) => {
                  allTests.forEach((tests) => {
                    tests.length.should.be.above(0);
                  });
                  done();
                })
                .catch(done);
            });
        })
        .catch(done);
    });
  });

  // 生成某个文件的测试用例
  benchmarks.forEach((benchmark) => {
    it(`it should generate test of one file in ${benchmark.name}`, function (done) {
      let projectVersion;
      let allFunctions;
      let fileId;
      project.createRandomVersion()
        .then((res) => {
          projectVersion = res;
          return projectVersion.getAllFunctions(benchmark);
        })
        .then((res) => {
          fileId = res[0].fileId;
          allFunctions = res;
          return project.creator.login();
        })
        .then(() => {
          chai.request(uri)
            .post(url(projectVersion.versionId))
            .query({ fileIds: fileId })
            .set('Authorization', `Bearer ${project.creator.token.accessToken}`)
            .end((err, res) => {
              res.should.have.status(202);
              common.should.be.taskMessage(res.body);
              res.body.type.should.be.eql(tasks.type.testCaseGenerate);
              res.body.status.should.be.eql(tasks.statusKind.waiting);
              res.body.progress.should.be.eql(0);

              project.creator.waiting4TasksOfVersionFinished(projectVersion.versionId)
                .then(() => {
                  // 查询测试用例
                  const promises = allFunctions.map((func) => {
                    const { functionId } = func;
                    return new Promise((resolve, reject) => {
                      chai.request(uri)
                        .get(`/functions/${functionId}/tests.json`)
                        .set('Authorization', `Bearer ${project.creator.token.accessToken}`)
                        .end((err, res) => {
                          err ? reject(err) : resolve(res.body.tests);
                        });
                    });
                  });
                  return Promise.all(promises);
                })
                .then((allTests) => {
                  allFunctions.forEach((func, index) => {
                    if (func.fileId === fileId) {
                      allTests[index].length.should.be.above(0);
                    } else {
                      allTests[index].length.should.be.eql(0);
                    }
                  });
                  done();
                })
                .catch(done);
            });
        })
        .catch(done);
    });
  });

  // 生成某个函数的测试用例
  benchmarks.forEach((benchmark) => {
    it(`it should generate test of one function in ${benchmark.name}`, function (done) {
      let projectVersion;
      let allFunctions;
      let functionId;
      project.createRandomVersion()
        .then((res) => {
          projectVersion = res;
          return projectVersion.getAllFunctions(benchmark);
        })
        .then((res) => {
          functionId = res[0].functionId;
          allFunctions = res;
          return project.creator.login();
        })
        .then(() => {
          chai.request(uri)
            .post(url(projectVersion.versionId))
            .query({ functionIds: functionId })
            .set('Authorization', `Bearer ${project.creator.token.accessToken}`)
            .end((err, res) => {
              res.should.have.status(202);
              common.should.be.taskMessage(res.body);
              res.body.type.should.be.eql(tasks.type.testCaseGenerate);
              res.body.status.should.be.eql(tasks.statusKind.waiting);
              res.body.progress.should.be.eql(0);

              project.creator.waiting4TasksOfVersionFinished(projectVersion.versionId)
                .then(() => {
                  // 查询测试用例
                  const promises = allFunctions.map((func) => {
                    const { functionId } = func;
                    return new Promise((resolve, reject) => {
                      chai.request(uri)
                        .get(`/functions/${functionId}/tests.json`)
                        .set('Authorization', `Bearer ${project.creator.token.accessToken}`)
                        .end((err, res) => {
                          err ? reject(err) : resolve(res.body.tests);
                        });
                    });
                  });
                  return Promise.all(promises);
                })
                .then((allTests) => {
                  allFunctions.forEach((func, index) => {
                    if (func.functionId === functionId) {
                      allTests[index].length.should.be.above(0);
                    } else {
                      allTests[index].length.should.be.eql(0);
                    }
                  });
                  done();
                })
                .catch(done);
            });
        })
        .catch(done);
    });
  });

  // 没有函数可以解析
  benchmarks.forEach((benchmark) => {
    it(`it should fail when no function to generate of ${benchmark.name}`, function (done) {
      let projectVersion;
      project.createRandomVersion()
        .then((res) => {
          projectVersion = res;
          return projectVersion.getAllFunctions(benchmark);
        })
        .then(() => project.creator.login())
        .then(() => {
          chai.request(uri)
            .post(url(projectVersion.versionId))
            .set('Authorization', `Bearer ${project.creator.token.accessToken}`)
            .query({ exceptFileIds: [projectVersion.rootDirectory.fileId] })
            .end((err, res) => {
              res.should.have.status(400);
              common.should.be.errorMessage(res.body);
              done();
            });
        })
        .catch(done);
    });
  });

  // 不可生成冻结项目的测试用例
  it('it should fail to generate tests in frozen project', function (done) {
    let newProjectId;
    let newVersionId;
    project.creator.createRandomProject()
      .then((project) => {
        newProjectId = project.projectId;
        return project.createRandomVersion();
      })
      .then(({ versionId }) => {
        newVersionId = versionId;
        return project.creator.freezeProject(newProjectId);
      })
      .then(() => project.creator.login())
      .then(() => {
        chai.request(uri)
          .post(url(newVersionId))
          .set('Authorization', `Bearer ${project.creator.token.accessToken}`)
          .end((err, res) => {
            res.should.have.status(403);
            common.should.be.errorMessage(res.body);
            done();
          });
      })
      .catch(done);
  });

  // 不可生成冻结项目版本中的测试用例
  it('it should fail to generate tests in frozen project version', function (done) {
    let newVersionId;
    project.createRandomVersion()
      .then(({ versionId }) => {
        newVersionId = versionId;
        return project.freezeVersion(versionId);
      })
      .then(() => project.creator.login())
      .then(() => {
        chai.request(uri)
          .post(url(newVersionId))
          .set('Authorization', `Bearer ${project.creator.token.accessToken}`)
          .end((err, res) => {
            res.should.have.status(403);
            common.should.be.errorMessage(res.body);
            done();
          });
      })
      .catch(done);
  });

  // 不可生成他人项目的测试用例
  it('it should fail to generate tests when the project is not yours', function (done) {
    let otherVersionId;
    administrator.createRandomTester()
      .then((tester) => {
        newUserIds.push(tester.userId);
        return tester.createRandomProject();
      })
      .then((project) => project.createRandomVersion())
      .then(({ versionId }) => {
        otherVersionId = versionId;
        return project.creator.login();
      })
      .then(() => {
        chai.request(uri)
          .post(url(otherVersionId))
          .set('Authorization', `Bearer ${project.creator.token.accessToken}`)
          .end((err, res) => {
            res.should.have.status(404);
            common.should.be.errorMessage(res.body);
            done();
          });
      })
      .catch(done);
  });

  // 不可生成不存在的项目文件的测试用例
  it('it should fail to generate tests when the project is not exist', function (done) {
    let newProjectId;
    let newVersionId;
    project.creator.createRandomProject()
      .then((project) => {
        newProjectId = project.projectId;
        return project.createRandomVersion();
      })
      .then(({ versionId }) => {
        newVersionId = versionId;
        return project.creator.removeProject(newProjectId);
      })
      .then(() => project.creator.login())
      .then(() => {
        chai.request(uri)
          .post(url(newVersionId))
          .set('Authorization', `Bearer ${project.creator.token.accessToken}`)
          .end((err, res) => {
            res.should.have.status(404);
            common.should.be.errorMessage(res.body);
            done();
          });
      })
      .catch(done);
  });
});
